import {useEffect, useState} from 'react';
import {Input, Button, Layout, List, Modal} from 'antd';
import ChatMessage from './components/ChatMessage';
import axios from "axios";
import Swal from 'sweetalert2';

const { Footer, Content } = Layout;

interface Message {
    content: string;
    isUser: boolean;
}


export default function App() {
    const [messages, setMessages] = useState<Message[]>([

    ]);
    const [questionId, setQuestionId] = useState<string>();
    const [inputText, setInputText] = useState('');
    const [guessModalVisible, setGuessModalVisible] = useState(false);
    const [guessText, setGuessText] = useState('');
    useEffect(() => {
        // 调用AI获取题面
        axios.get("http://localhost:8080/ai/title").then(
            (resp) => {
                const result = resp.data;
                if (result.code === 0) {
                    setMessages([
                        {
                            content: result.data.title,
                            isUser: false
                        }
                    ]);
                    setQuestionId(result.data.id);
                } else {
                    console.log("系统错误");
                }
            }
        )
    }, [])

    // 处理真相提交
    const handleSubmitGuess = async () => {
        try {
            if (!guessText.trim()) {
                Swal.fire('提示', '请输入你的推理结论！', 'warning');
                return;
            }
            const resp = await axios.post('/ai/reduce', {
                answer: guessText
            });
            const isCorrect = resp.data
            if (isCorrect) {
                Swal.fire('🎉 恭喜', '答案正确！即将结束游戏', 'success');
                // 游戏结束逻辑...
            } else {
                Swal.fire('❌ 错误', '请继续推理', 'error');
            }

            setGuessModalVisible(false);
            setGuessText('');
        } catch (error) {
            Swal.fire('错误', '提交失败，请重试', 'error');
        }
    };

    const handleSend = () => {
        if (!inputText.trim()) return;

        // 添加用户消息
        setMessages(prev => [...prev, { content: inputText, isUser: true }]);

        // AI回复
        axios.post("http://localhost:8080/ai/question", {
            id: questionId,
            question: inputText,
        }).then((resp) => {
            const result = resp.data;
            if (result.code === 0) {
                const aiResponse = result.data
                setMessages(prev => [...prev, {
                    content: `${aiResponse}`,
                    isUser: false
                }]);
            } else {
                console.log("系统错误");
            }
        });
        setInputText('');
    };

    const mockAIResponse = (text: string) => {
        // 这里可以替换为你的AI逻辑
        const responses = ["是", "否", "与此无关"];
        if(text.includes("弹珠")) return "与此无关";
        if(text.includes("报警")) return "是";
        return responses[Math.floor(Math.random() * responses.length)];
    };

    return (
        <Layout style={{ height: '100vh' }}>
            <Content style={{ overflowY: 'auto', padding: '20px' }}>
                <div style={{ maxWidth: '800px', margin: '0 auto' }}>
                    {messages.map((msg, index) => (
                        <ChatMessage
                            key={index}
                            content={msg.content}
                            isUser={msg.isUser}
                        />
                    ))}
                </div>
            </Content>

            <Footer style={{ background: '#fff', padding: '16px' }}>
                <div style={{ display: 'flex', gap: '10px' }}>
                    <Input
                        value={inputText}
                        onChange={(e) => setInputText(e.target.value)}
                        placeholder="输入你的问题..."
                        onPressEnter={handleSend}
                    />
                    <Button type="primary" onClick={handleSend}>
                        发送
                    </Button>
                    <Button
                        danger
                        onClick={() => setGuessModalVisible(true)}
                    >
                        还原真相
                    </Button>
                </div>
            </Footer>
            <Modal
                title="还原真相"
                open={guessModalVisible}
                onOk={handleSubmitGuess}
                onCancel={() => setGuessModalVisible(false)}
                okText="提交验证"
                cancelText="取消"
                destroyOnClose
                centered
            >
                <Input.TextArea
                    value={guessText}
                    onChange={(e) => setGuessText(e.target.value)}
                    placeholder="请输入你推理的完整真相..."
                    autoSize={{ minRows: 4, maxRows: 6 }}
                    showCount
                    maxLength={500}
                />
            </Modal>
        </Layout>
    );
}